/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlUtils {

    public static void marshalXml(Object obj, String filePath) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller mar = context.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            File file = new File(filePath);
            mar.marshal(obj, file);
        } catch (JAXBException ex) {
            System.out.println(ex.getMessage());
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String marshalXml(Object obj) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller mar = context.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            StringWriter sw = new StringWriter();
            mar.marshal(obj, sw);
            return sw.toString();
        } catch (JAXBException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public static String transformToString(String xmlPath) {
        FileInputStream fis = null;
        String result = "";
        try {
            fis = new FileInputStream(xmlPath);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
            while (true) {
                String s = br.readLine();
                if (s == null) {
                    break;
                } else {
                    result += s;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return result;
    }

    public static String transformToString(String xslPath, String xmlPath) {
        String result = "";
        try {
            StreamSource xslStream = new StreamSource(xslPath);
            StreamSource xmlStream = new StreamSource(xmlPath);
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer(xslStream);
            StringWriter sw = new StringWriter();
            StreamResult rs = new StreamResult(sw);
            tf.transform(xmlStream, rs);
            result = sw.toString();
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public static String transformToString(String xslPath, Source xmlSource) {
        String result = "";
        try {
            StreamSource xslStream = new StreamSource(xslPath);
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer(xslStream);
            StringWriter sw = new StringWriter();
            StreamResult rs = new StreamResult(sw);
            tf.transform(xmlSource, rs);
            result = sw.toString();
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public static String transformToString(String xslPath, String xmlPath, Map<String, Object> param) {
        String result = "";
        try {
            StreamSource xslStream = new StreamSource(xslPath);
            StreamSource xmlStream = new StreamSource(xmlPath);
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer(xslStream);
            StringWriter sw = new StringWriter();
            StreamResult rs = new StreamResult(sw);
            Set<String> keys = param.keySet();
            for (String key : keys) {
                tf.setParameter(key, param.get(key));
            }
            tf.transform(xmlStream, rs);
            result = sw.toString();
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public static String transformToString(String xslPath, Source xmlSource, Map<String, Object> param) {
        String result = "";
        try {
            StreamSource xslStream = new StreamSource(xslPath);
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer(xslStream);
            StringWriter sw = new StringWriter();
            StreamResult rs = new StreamResult(sw);
            Set<String> keys = param.keySet();
            for (String key : keys) {
                tf.setParameter(key, param.get(key));
            }
            tf.transform(xmlSource, rs);
            result = sw.toString();
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public static Object unMarshalXml(String xsdPath, String xmlPath, Class boundClass) {
        try {
            JAXBContext jc = JAXBContext.newInstance(boundClass);
            Unmarshaller u = jc.createUnmarshaller();

            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema sm = sf.newSchema(new File(xsdPath));
            u.setSchema(sm);

            File f = new File(xmlPath);
            Object obj = u.unmarshal(f);
            return obj;
        } catch (SAXException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static Object unMarshalXml(String xsdPath, Source source, Class boundClass) {
        try {
            JAXBContext jc = JAXBContext.newInstance(boundClass);
            Unmarshaller u = jc.createUnmarshaller();
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema sm = sf.newSchema(new File(xsdPath));
            u.setSchema(sm);

            Object obj = u.unmarshal(source);
            return obj;
        } catch (SAXException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static Node parseDOM(String xmlFile) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new File(xmlFile));
            return doc;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static Node getOneNode(Node document, String path) {
        try {
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xp = xpf.newXPath();
            Node nodes = (Node) xp.evaluate(path, document, XPathConstants.NODE);
            return nodes;
        } catch (XPathExpressionException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static Node parseDOMFromString(String xmlContent) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(new StringReader(xmlContent)));
            return doc;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } 
        return null;
    }

    public static Node getOneNodeFromDom(Node document, String xPathExpression) {
        try {
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xp = xpf.newXPath();
            Node nodes = (Node) xp.evaluate(xPathExpression, document, XPathConstants.NODE);
            return nodes;
        } catch (XPathExpressionException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
